package com.selfdriving.wl.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.selfdriving.BaseFragmentActivity;
import com.selfdriving.R;
import com.selfdriving.activity.AboutMeMyComment;
import com.selfdriving.activity.ActivityMyFriends;
import com.selfdriving.activity.ActivityWriteTravelNotes;
import com.selfdriving.activity.MyAttentionActivity;
import com.selfdriving.activity.MySettingActivity;
import com.selfdriving.activity.RegisterActivity;
import com.selfdriving.bean.Entity;
import com.selfdriving.bean.MyArticle;
import com.selfdriving.bean.MyFile;
import com.selfdriving.bean.User;
import com.selfdriving.utils.BitmapUtil;
import com.selfdriving.utils.Constant;
import com.selfdriving.utils.Utils;
import com.selfdriving.utils.WriteCamera1;
import com.selfdriving.view.MoMoRefreshListView.OnCancelListener;
import com.selfdriving.view.MoMoRefreshListView.OnRefreshListener;

public class ActivityAboutMe extends BaseFragmentActivity implements
		OnClickListener, OnRefreshListener, OnCancelListener
{
	private List<View> listViews; // Tab页面列表
	private ViewPager mPager;// 页卡内容
	private ImageView cursor;// 动画图片
	private Button btn1, btn2, btn3;// 页卡头标
	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int bmpW;// 动画图片宽度
	WriteInScenic writeInScenic;
	AboutMe aboutMe;
	SystemSet systemSet;
	List<Entity> dates = new ArrayList<Entity>();
	private TextView title;
	private int page = 1;
	private boolean isLoading = false;
	public static boolean isLoadingDatas = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.w_activity_about_me_page);
		Utils.checkLoading(mApplication, this);
		if (isLogin())
		{
			isLoading = true;
		} else
		{
			isLoading = false;
		}
		initViews();
		initEvents();
		InitImageView();
		InitViewPager();
	}

	@Override
	protected void initViews()
	{
		btn1 = (Button) findViewById(R.id.about_me_but1);
		btn2 = (Button) findViewById(R.id.about_me_but2);
		btn3 = (Button) findViewById(R.id.about_me_but3);
		title = (TextView) findViewById(R.id.top_text);
		title.setText("关于我");
	}

	@Override
	protected void initEvents()
	{
		btn1.setOnClickListener(new MyOnClickListener(0));
		btn2.setOnClickListener(new MyOnClickListener(1));
		btn3.setOnClickListener(new MyOnClickListener(2));
	}

	/** 初始化动画 **/
	private void InitImageView()
	{
		cursor = (ImageView) findViewById(R.id.cursor);
		offset = (mScreenWidth / 3 - bmpW) / 2;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);// 设置动画初始位置
	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		getdatas();

	}

	public void getdatas()
	{
		if (dates.size() < 1 || isLoadingDatas)
		{
			if (isLogin())
			{
				page = 1;
				getListDatas(false);
				fb.display(writeInScenic.avatar, mApplication.user.getIcon());
				writeInScenic.userName.setText(mApplication.user.getName());
			}
		}
	}

	/** 初始化ViewPager **/
	private void InitViewPager()
	{
		mPager = (ViewPager) findViewById(R.id.vPager);
		listViews = new ArrayList<View>();
		writeInScenic = new WriteInScenic(mApplication, this, this, dates,
				this, isLoading, this, this);
		aboutMe = new AboutMe(mApplication, this, this);
		systemSet = new SystemSet(mApplication, this);
		listViews.add(writeInScenic.getView());
		listViews.add(aboutMe.getView());
		listViews.add(systemSet.getView());
		mPager.setAdapter(new MyPagerAdapter(listViews));
		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
		if (isLoading)
		{
			page = 1;
			getListDatas(false);
		}
	}

	public void getListDatas(final boolean loadMost)
	{
		if (!loadMost)
		{
			dates.clear();
		}
		isLoadingDatas = false;
		writeInScenic.listView.mState = 2;
		writeInScenic.listView.changeHeaderViewByState();
		writeInScenic.noLoading.setVisibility(View.GONE);
		AjaxParams params = new AjaxParams();
		params.put("f", "64");
		params.put("phone", mApplication.user.getPhone());
		params.put("page", "" + page);
		FinalHttp fh = new FinalHttp();
		fh.configTimeout(10000);
		fh.post(Constant.POST, params, new AjaxCallBack<Object>()
		{
			@Override
			public void onFailure(Throwable t, String strMsg)
			{
				showShortToast("获取信息失败");
				writeInScenic.listView.onRefreshComplete();
				writeInScenic.listView.onLoadMoreComplete(false);
			}

			@Override
			public void onSuccess(Object o)
			{
				String json = o.toString();
				if (!json.contains("empty"))
				{
					try
					{
						MyArticle myArticle;
						JSONArray jsonArray = new JSONArray(json);
						for (int i = 0; i < jsonArray.length(); i++)
						{
							JSONObject object = jsonArray.getJSONObject(i);
							String id = object.getString("id");
							String title = object.getString("title");
							String headImg = object.getString("headImg");
							String uname = object.getString("uname");
							String times = object.getString("times");
							String laud = object.getString("laud");
							String marrow = object.getString("marrow");
							String clicks = object.getString("clicks");
							String review = object.getString("review");
							String img = object.getString("img");
							myArticle = new MyArticle(id, title, headImg,
									uname, times, laud, marrow, clicks, review,
									img);
							dates.add(myArticle);
						}
						writeInScenic.adapter.notifyDataSetChanged();
						writeInScenic.listView.onRefreshComplete();
						writeInScenic.listView.onLoadMoreComplete(false);
						if (dates.size() > 5
								&& writeInScenic.listView.getFooterViewsCount() == 0)
						{
							writeInScenic.listView
									.addFooterView(writeInScenic.listView.mFootView);
						}
						page++;
					} catch (JSONException e)
					{
						showShortToast("获取信息失败");
						writeInScenic.listView.onRefreshComplete();
						writeInScenic.listView.onLoadMoreComplete(false);
					}
				} else
				{
					writeInScenic.listView.onRefreshComplete();
					writeInScenic.listView.onLoadMoreComplete(false);
				}
			}
		});
	}

	/**
	 * ViewPager适配器
	 */
	public class MyPagerAdapter extends PagerAdapter
	{
		public List<View> mListViews;
		public int mCount;

		public MyPagerAdapter(List<View> mListViews)
		{
			this.mListViews = mListViews;
			mCount = mListViews.size();
		}

		public void destroyItem(View collection, int position, Object arg2)
		{
			((ViewPager) collection).removeView(mListViews.get(position));
			if (position >= mListViews.size())
			{
				int newPosition = position % mListViews.size();
				position = newPosition;
			}
			if (position < 0)
			{
				position = -position;
			}
		}

		public void finishUpdate(View arg0)
		{
		}

		public int getCount()
		{
			// return mListViews.size();
			return mCount;// 更改实现无限循环
		}

		public Object instantiateItem(View collection, int position)
		{
			try
			{
				((ViewPager) collection).addView(mListViews.get(position), 0);
			} catch (Exception e)
			{
			}
			return mListViews.get(position);
		}

		public boolean isViewFromObject(View arg0, Object arg1)
		{
			return arg0 == (arg1);
		}

		public void restoreState(Parcelable arg0, ClassLoader arg1)
		{
		}

		public Parcelable saveState()
		{
			return null;
		}

		public void startUpdate(View arg0)
		{
		}
	}

	/**
	 * 头标点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener
	{
		private int index = 0;

		public MyOnClickListener(int i)
		{
			index = i;
		}

		public void onClick(View v)
		{
			mPager.setCurrentItem(index);
		}
	};

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener
	{

		int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量
		int two = one * 2;// 页卡1 -> 页卡3 偏移量

		public void onPageSelected(int arg0)
		{
			Animation animation = null;
			switch (arg0)
			{
			case 0:
				btn1.setTextColor(getResources().getColor(R.color.white));
				btn2.setTextColor(getResources().getColor(R.color.title));
				btn3.setTextColor(getResources().getColor(R.color.title));
				if (currIndex == 1)
				{
					animation = new TranslateAnimation(one, 0, 0, 0);
				} else if (currIndex == 2)
				{
					animation = new TranslateAnimation(two, 0, 0, 0);
				}
				break;
			case 1:
				btn1.setTextColor(getResources().getColor(R.color.title));
				btn2.setTextColor(getResources().getColor(R.color.white));
				btn3.setTextColor(getResources().getColor(R.color.title));
				if (currIndex == 0)
				{
					animation = new TranslateAnimation(offset, one, 0, 0);
				} else if (currIndex == 2)
				{
					animation = new TranslateAnimation(two, one, 0, 0);
				}
				break;
			case 2:
				btn1.setTextColor(getResources().getColor(R.color.title));
				btn2.setTextColor(getResources().getColor(R.color.title));
				btn3.setTextColor(getResources().getColor(R.color.white));
				if (currIndex == 0)
				{
					animation = new TranslateAnimation(offset, two, 0, 0);
				} else if (currIndex == 1)
				{
					animation = new TranslateAnimation(one, two, 0, 0);
				}
				break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}

		public void onPageScrolled(int arg0, float arg1, int arg2)
		{
		}

		public void onPageScrollStateChanged(int arg0)
		{
		}
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.personge_avatar:
			rlAlterAvatar();
			break;
		case R.id.myComment:
			rlMyComment();
			break;
		case R.id.rlAttention:
			rlMyAttention();
			break;
		case R.id.rlMyAttention:
			rlAttention();
			break;
		case R.id.rlMyfriend:
			rlMyfriend();
			break;
		case R.id.rlMySetting:
			rlMySetting();
			break;
		case R.id.strategy_write:
			if (isLogin())
			{
				Intent intent = new Intent(this, ActivityWriteTravelNotes.class);
				startActivityForResult(intent, 1);
			} else
			{
				startActivity(RegisterActivity.class);
			}
			break;
		case R.id.not_loading_but:
			startActivity(RegisterActivity.class);
			break;
		}

	}

	/** 【景点随写】修改头像 */
	public void rlAlterAvatar()
	{
		if (!isLogin())
		{
			startActivity(RegisterActivity.class);
		} else
		{
			new WriteCamera1(this, this);
		}
	}

	/** 【关于我】我的点评 */
	public void rlMyComment()
	{
		if (!isLogin())
		{
			startActivity(RegisterActivity.class);
		} else
		{
			startActivity(AboutMeMyComment.class);
		}
	}

	/** 【关于我】我的关注 */
	public void rlMyAttention()
	{
		if (!isLogin())
		{
			startActivity(RegisterActivity.class);
		} else
		{
			startActivity(MyAttentionActivity.class);
		}
	}

	/** 【关于我】关注我的 */
	public void rlAttention()
	{
		if (!isLogin())
		{
			startActivity(RegisterActivity.class);
		} else
		{
			startActivity(MyAttentionActivity.class);
		}
	}

	/** 【关于我】我的好友 */
	public void rlMyfriend()
	{
		if (!isLogin())
		{
			startActivity(RegisterActivity.class);
		} else
		{
			startActivity(ActivityMyFriends.class);
		}
	}

	/** 【关于我】我的设置 */
	public void rlMySetting()
	{
		if (!isLogin())
		{
			startActivity(RegisterActivity.class);
		} else
		{
			startActivity(MySettingActivity.class);
		}
	}

	@Override
	public void onCancel()
	{
		// TODO Auto-generated method stub
		writeInScenic.listView.onRefreshComplete();
	}

	@Override
	public void onRefresh()
	{
		// TODO Auto-generated method stub
		if (isLogin())
		{
			page = 1;
			getListDatas(false);
		} else
		{
			showShortToast("当前未登录");
			writeInScenic.listView.onRefreshComplete();
		}
	}

	@Override
	public void onLoadMore()
	{
		// TODO Auto-generated method stub
		if (isLogin())
		{
			getListDatas(true);
		} else
		{
			showShortToast("当前未登录");
			writeInScenic.listView.onRefreshComplete();
			writeInScenic.listView.onLoadMoreComplete(false);
		}
	}

	/**
	 * 系统裁剪照片
	 * 
	 * @param uri
	 */
	private void startPhotoZoom(Uri uri)
	{
		// 获得系统剪切图片
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("scale", true);
		intent.putExtra("noFaceDetection", true);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, Constant.CROP_FROM_FILE1);
	}

	/**
	 * 保存裁剪的照片
	 * 
	 * @param data
	 */
	private void saveCropPhoto(Intent data)
	{
		Bundle extras = data.getExtras();
		if (extras != null)
		{
			Bitmap bitmap = extras.getParcelable("data");
			postAvatar(bitmap);
		} else
		{
			Toast.makeText(this, "获取裁剪照片错误", Toast.LENGTH_SHORT).show();
		}
	}

	static File saveBitmap2file(Bitmap bmp, String filename)
	{
		File file = null;
		CompressFormat format = Bitmap.CompressFormat.JPEG;
		int quality = 100;
		OutputStream stream = null;
		try
		{
			stream = new FileOutputStream("/sdcard/" + filename + ".jpg");
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (bmp.compress(format, quality, stream))
		{
			file = new File("/sdcard/" + filename + ".jpg");
		}
		return file;
	}

	/** 上传头像 */
	public void postAvatar(final Bitmap bitmap)
	{
		MyFile myFile = new MyFile("avatar", saveBitmap2file(bitmap, "avatar"));
		AjaxParams params = new AjaxParams();
		params.put("f", "70");
		params.put("phone", mApplication.user.getPhone());
		try
		{
			params.put(myFile.getFileName(), myFile.getFile());
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		showLoadingDialog("头像上传中...");
		FinalHttp fh = new FinalHttp();
		fh.configTimeout(10000);
		fh.post(Constant.POST, params, new AjaxCallBack<Object>()
		{
			@Override
			public void onFailure(Throwable t, String strMsg)
			{
				showShortToast("服务器连接失败");
				dismissLoadingDialog();
			}

			@Override
			public void onSuccess(Object o)
			{
				String json = o.toString();
				if (json.contains("000000"))
				{
					showShortToast("头像上传成功");
					try
					{
						JSONObject object = new JSONObject(json);
						String img = object.getString("img");
						String phone = mApplication.user.getPhone();
						String name = mApplication.user.getName();
						String pwd = mApplication.user.getPwd();
						double lat = mApplication.user.getLag();
						double lng = mApplication.user.getLng();
						mApplication.user = new User(img, phone, name, pwd,
								lat, lng);
						writeInScenic.avatar.setImageBitmap(bitmap);
					} catch (JSONException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else
				{
					showShortToast("头像上传失败");
				}
				dismissLoadingDialog();
			}
		});
	}

	public String getRealPathFromURI(Uri contentUri)
	{
		String res = null;
		if (contentUri != null)
		{
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(contentUri, proj, null,
					null, null);
			if (cursor != null)
			{
				if (cursor.moveToFirst())
				{
					int column_index = cursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					res = cursor.getString(column_index);
				}
				cursor.close();
			}
		}
		return res;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode)
		{
		case RESULT_OK:
			isLoadingDatas = true;
			break;
		}
		switch (requestCode)
		{
		case Constant.PICK_FROM_FILE1:// 取得本地图片
			if (data == null)
			{
				return;
			}
			Constant.imageCaptureUri = data.getData();
			Constant.fileRealPath = getRealPathFromURI(Constant.imageCaptureUri);
			Bitmap bitmap = BitmapUtil.getSamplingImage(Constant.fileRealPath);
			if (bitmap != null)
			{
			}
			startPhotoZoom(Constant.imageCaptureUri);
			break;
		case Constant.PICK_FROM_CAMERA1:// 拍照
			Constant.fileRealPath = Constant.imageCaptureUri.getPath();
			bitmap = BitmapUtil.getSamplingImage(Constant.fileRealPath);
			startPhotoZoom(Constant.imageCaptureUri);
		case Constant.CROP_FROM_FILE1:
			if (data == null)
			{
				return;
			} else
			{
				saveCropPhoto(data);
			}
			break;
		}
	}
}
